// ==UserScript==
// @name         Fuck you, zhihu
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  屏蔽进入知乎专栏和问题时弹出的登录框。
// @author       cheer <doktor_katze@yeah.net>
// @match        https://zhuanlan.zhihu.com/p/*
// @match        https://www.zhihu.com/question/*
// @match        https://www.zhihu.com/topic/**
// @icon         https://static.zhihu.com/heifetz/favicon.ico
// @grant        GM_log
// ==/UserScript==

(function () {
    'use strict'

    function queryElement(element, className, timeout) {
        let observer
        const p1 = new Promise((resolve, reject) => {
            const elements = element.getElementsByClassName(className)
            if (elements.length) {
                resolve(elements[0])
                return
            }

            observer = new MutationObserver(mutations => {
                let nodeFound = null
                for (const mutation of mutations) {
                    const len = mutation?.addedNodes?.length
                    if (!len) {
                        continue
                    }
                    // console.log(mutation.addedNodes)
                    for (let i = 0; i < len; i++) {
                        const node = mutation.addedNodes[0]
                        const elements = node?.getElementsByClassName(className)
                        if (elements?.length) {
                            nodeFound = elements[0]
                            break
                        }
                    }

                    if (nodeFound) {
                        break
                    }
                }

                if (nodeFound) {
                    resolve(nodeFound)
                    observer.disconnect()
                }
            })

            observer.observe(element, {
                childList: true,
                subtree: true,
                attributes: false,
                characterData: false
            })
        })

        const p2 = new Promise((resolve, reject) => setTimeout(() => resolve(null), timeout))
        return Promise.race([p1, p2]).finally(() => observer?.disconnect())
    }

    async function main() {
        const element = await queryElement(document.body, 'Modal-closeButton', 15000)
        if (element) {
            element.click()
            GM_log('成功屏蔽了讨人厌的登录框。')
        }
    }
    main()
})()